package com.jmb.waimao.controller;

import com.icegreen.greenmail.util.GreenMail;
import com.jmb.waimao.service.EmailSendingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller for testing email functionality
 */
@RestController
@RequestMapping("/api/mail-test")
@Slf4j
public class MailTestController {

    @Autowired
    private EmailSendingService emailSendingService;

    @Autowired
    private GreenMail greenMail;

    /**
     * Send a test email
     *
     * @param to Recipient email address
     * @param subject Email subject
     * @param content Email content
     * @return Result of the operation
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendTestEmail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content) {

        log.info("Sending test email to: {}", to);

        boolean success = emailSendingService.sendEmail(to, subject, content);

        Map<String, Object> result = new HashMap<>();
        result.put("success", success);

        if (success) {
            result.put("message", "Email sent successfully");
        } else {
            result.put("message", "Failed to send email");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * Get received emails
     *
     * @return List of received emails
     */
    @GetMapping("/received")
    public ResponseEntity<Map<String, Object>> getReceivedEmails() {
        Map<String, Object> result = new HashMap<>();

        try {
            MimeMessage[] receivedMessages = greenMail.getReceivedMessages();

            result.put("success", true);
            result.put("count", receivedMessages.length);

            // Extract basic information from messages
            Map<String, Object>[] messages = new Map[receivedMessages.length];
            for (int i = 0; i < receivedMessages.length; i++) {
                MimeMessage message = receivedMessages[i];
                Map<String, Object> messageInfo = new HashMap<>();

                try {
                    messageInfo.put("from", Arrays.toString(message.getFrom()));
                    messageInfo.put("to", Arrays.toString(message.getAllRecipients()));
                    messageInfo.put("subject", message.getSubject());
                    messageInfo.put("sentDate", message.getSentDate());
                } catch (MessagingException e) {
                    log.error("Error extracting message info", e);
                    messageInfo.put("error", "Failed to extract message details");
                }

                messages[i] = messageInfo;
            }

            result.put("messages", messages);

        } catch (Exception e) {
            log.error("Error retrieving received emails", e);
            result.put("success", false);
            result.put("message", "Failed to retrieve received emails: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    /**
     * Clear all received emails
     *
     * @return Result of the operation
     */
    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearEmails() {
        Map<String, Object> result = new HashMap<>();

        try {
            // Reset the mail store
            greenMail.purgeEmailFromAllMailboxes();
            result.put("success", true);
            result.put("message", "All emails cleared successfully");
        } catch (Exception e) {
            log.error("Error clearing emails", e);
            result.put("success", false);
            result.put("message", "Failed to clear emails: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }
}
